import React, {useContext, useEffect, useState} from 'react';
import { HomeTwoTone, CarTwoTone, HeartTwoTone } from '@ant-design/icons';
import { Badge} from 'antd';
import './ProductPage.css';
import {useNavigate, useParams} from 'react-router-dom';
import {loadProductList, loadShoppingCarProducts} from "../../services/data";
import {getProductList} from "../../services/product";
import {GlobalContext} from "../../contexts/GlobalContext";
import {Toast} from "antd-mobile";

const HelpComponent = () => {
    const [isProductListLoaded, setIsProductListLoaded] = useState(false);
    //const [count, setCount] = useState(0);
    const [productCount, setProductCount] = useState(() => {
        // 从 localStorage 中读取 productCount 的初始值，如果不存在则默认为空对象
        return JSON.parse(localStorage.getItem("productCount")) || {};
    });
    const navigate = useNavigate();
    const { user } = useContext(GlobalContext);

    const [productList, setProductList] = useState([]);

    useEffect(() => {
        fetchProductList();
    }, []);

    const fetchProductList = (page, pageSize) => {
        // 获取商品列表示例
        getProductList({ page: 1, pageSize: 10 }).then(response => {
            if (response && response.result) {
               // console.log('Product List:', response.result);
                setProductList(response.result);
                setIsProductListLoaded(true);
            } else {
                console.error('Error fetching product list: Invalid response');
            }
        }).catch(error => {
            console.error('Error fetching product list:', error);
        });

    };



    //-----------燕子的逻辑在注释掉的部分-------------------------------------
    // loadProductList();
    loadShoppingCarProducts();
    // const productList = JSON.parse(localStorage.getItem("productList"));
    const cart = JSON.parse(localStorage.getItem("cart")) || [];
    const {id} = useParams();
    const numberId = Number(id);

    //找到当前页面对应的商品，查看购物车中是否存在该商品，如果存在，则更新count，如果不存在且当前商品数量非0（表示要加到购物车中），则结果添加到购物车中
    useEffect(() => {
        // fetchProductList();
        // console.log('获取的列表',productList);
        // const product = productList.filter(item => item.id === numberId)[0];
        const product = productList.find(item => item.id === numberId);
        if (product) { // 确保 product 不是 undefined
            console.log(numberId);
            console.log('product',product);
            const existingProductIndex = cart.findIndex(item => item.id === product.id);
            const currentCount = productCount[numberId] || 0;

            localStorage.setItem("productCount",JSON.stringify(productCount));
            if (existingProductIndex === -1) {
                if(currentCount){
                    let productWithCount = {
                        ...product,
                        count: currentCount,
                        isChecked: false,
                        isShow: true,
                    };
                    cart.push(productWithCount);
                }
            }else{
                const cartProduct = cart[existingProductIndex];
                cartProduct.count = currentCount;
            }
            localStorage.setItem("cart", JSON.stringify(cart));
            console.log("当前cart为：",cart);

        }else{
            console.error('Product not found for id:', numberId);
        }

    }, [productCount]);

    const increase = () => {
        if(localStorage.getItem("username")!=='user'){
            console.log(user.username)
            navigate('/login')
        }
        setProductCount(prevCounts => ({
            ...prevCounts,
            [numberId]: (prevCounts[numberId] || 0) + 1
        }));
    };
    const gotoOrder = () => {
        if (!productList || productList.length === 0) {
            console.error('Product list is not loaded.');
            return;
        }

        const orderList = JSON.parse(localStorage.getItem("orderList")) || [];
        console.log('orderList:', orderList);

        const product = productList.find(item => item.id === numberId);
        if (!product) {
            console.error('Product not found for id:', numberId);
            return;
        }
        product.count = 1;
        console.log('product:', product);
        const cost = product.price;

        let order = {
            orderId: orderList.length + 1,
            productList: [product],
            cost: cost,
            userId: 'user_001',
            address: '某某省,某某市,某某街道',
            discount: 0,
            shipping: 10,
            note: '请尽快发货',
            paymentMethod: '在线支付',
            submitTime: new Date(),
            status: '待付款'
        };
        orderList.push(order);
        console.log('orderList after push:', orderList);

        localStorage.setItem("orderList", JSON.stringify(orderList));
        navigate(`/order/${order.orderId}`);
    };


    const gotoShoppingCar = () => {
        navigate('/shoppingCar');
    };

    const gotohome =()=>{
        navigate('/home');
    }

    return (
        <div className="fixed-component">
            <div className="item" onClick={gotohome}>
                <HomeTwoTone twoToneColor="#FB5B40"/>
                <span className="name">首页</span>
            </div>
            <div className="item" onClick={gotoShoppingCar}>
                <Badge size="small" count={productCount[numberId]||0}>
                <CarTwoTone twoToneColor="#FB5B40"/>
                </Badge>
                <span className="name">购物车</span>
            </div>
            <div className="item">
                <HeartTwoTone twoToneColor="#FB5B40"/>
                <span className="name">收藏</span>
            </div>

            <div >
                <button className="gradient-button-buy" onClick={gotoOrder} disabled={!isProductListLoaded}>立即购买</button>
                <button className="gradient-button" onClick={increase}>加入购物车</button>
            </div>
        </div>)
};

export default HelpComponent;